// 发送验证码
import { ref } from "vue";
import http from "@/api/http.js";
import { ElMessage } from "element-plus";

export const useLoginHook = () => {
  const count = ref(0);
  const countLoading = ref(false);
  // type  0 = 手机号  1 = 邮箱
  const setCountDown = (i = 60, mobile, type = 0) => {
    countLoading.value = false;
    if (i > 0) {
      if (!mobile) {
        ElMessage.warning(
          `请输入${
            {
              0: "手机号",
              1: "邮箱",
            }[type]
          }`
        );
        return;
      }
      countLoading.value = true;
      const url = {
        0: "/sms/mobile",
        1: "/sms/email",
      }[type];
      const params = {
        lang: "zh",
        mobile,
        email: mobile,
      };
      http.get({ url, params }).then(() => {
          count.value = i;
          countLoading.value = false;
          const time = setInterval(() => {
            if (count.value <= 0) {
              clearInterval(time);
            }
            count.value--;
          }, 1000);
        },
        () => {
          count.value = 0;
          countLoading.value = false;
        }
      );
    } else {
      count.value = i;
    }
  };
  return {
    count,
    countLoading,
    setCountDown,
  };
};
